package com.wang.mvchain.outer.service.implay;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.HmacUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.HTTPUtil;
import com.wang.mvchain.outer.enums.TradeEnum;
import com.wang.mvchain.outer.service.ITradeService;

/**
 * bter的API工具
 * 
 * @author wangsh
 *
 */
public class GateTradeServiceImplay extends BaseTradeService implements ITradeService
{
	/* 服务器端的网址
	 * gateio.co
	 *  */
	private String serverUrl = "https://api.gateio.life" ; 
	private String dataServerUrl = "http://data.gateio.life" ; 
	
	//登陆验证的信息,可从网站模板中查找
	private JSONObject authJSON;
	
	@Override
	public int findWebsiteId()
	{
		return 15;
	}
	
	/**
	 * 获取签名方式
	 * 
	 * @return
	 */
	private String authSign(Map<String, String> condMap)
	{
		StringBuffer sb = new StringBuffer();
		for (Iterator iterator = condMap.entrySet().iterator(); iterator
				.hasNext();)
		{
			Entry me = (Entry) iterator.next();
			String key = me.getKey() + "";
			String value = me.getValue() + "";
			if ("requestURL".equalsIgnoreCase(key))
			{
				continue;
			}
			sb.append(key + "=" + value + "&");
		}
		
		/* 添加密钥 */
		String secretKey = "secret_key=" + authJSON.get("secretKey");
		
		if (sb.toString().lastIndexOf("&") != -1)
		{
			sb.delete(sb.lastIndexOf("&"), sb.length());
		}
		/* 放到请求体里面
		 * md5(键=值&键=值&secret_key=key)
		 *  */
		String md5Sign = sb.toString() + "&" + secretKey ; 
		md5Sign = DigestUtils.md5Hex(md5Sign);
		condMap.put("sign", md5Sign);
		
		/* sha256的sign
		 * 放到请求头中
		 * 
		 * sign=hmacsha512(键=值&键=值&sign=md5sign)
		 *  */
		String headSign = HmacUtils.hmacSha512Hex(authJSON.get("secretKey") + "", sb.toString() + "&sign=" + md5Sign);
		condMap.put("headSign", headSign);
		//ConstatFinalUtil.OUTER_LOG.info("原字符串:{};sign:{},headSign:",sb.toString(),md5Sign,headSign );
		return md5Sign ; 
	}
	
	/**
	 * 存储所有的参数,加密结果
	 * @param requestMap	请求参数中的所有数据
	 * @return	放到请求头中的信息
	 */
	private Map<String, String> authSignRes(Map<String, String> requestMap)
	{
		requestMap.put("api_key", authJSON.get("apiKey") + "");
		
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Key", authJSON.get("apiKey") + "");
		this.authSign(requestMap);
		
		headerMap.put("Key", authJSON.get("apiKey") + "");
		headerMap.put("Sign", requestMap.get("headSign"));
		/* 删除sign */
		requestMap.remove("headSign");
		return headerMap ; 
	}

	/**
	 * 获取用户基本信息
	 * 
	 * @return
	 */
	public JSONObject getUserInfo(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		
		Map<String, String> requestMap = new HashMap<String, String>();
		HTTPUtil httpUtil = new HTTPUtil();
		requestMap.put("requestURL", serverUrl + "/api2/1/private/balances");
		
		Map<String, String> headerMap = this.authSignRes(requestMap);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, requestMap);
			responseJSON = (JSONObject) JSON.parse(result.toLowerCase());
			if(responseJSON!=null && "true".equalsIgnoreCase(responseJSON.get("result") + ""))
			{	
				JSONObject dataJSON = new JSONObject();
				JSONObject balanceRes = (JSONObject) responseJSON.get("available");
				
				JSONObject balanceJSON = new JSONObject() ; 
				JSONObject lockedJSON = new JSONObject() ; 
				for (Iterator iterator = balanceRes.entrySet().iterator(); iterator.hasNext();)
				{
					Entry me = (Entry) iterator.next() ; 
					String key = me.getKey() + ""; 
					String value = me.getValue() + "" ;
					balanceJSON.put(key.toLowerCase(), value);
					lockedJSON.put(key.toLowerCase(), "0");
				}
				
				dataJSON.put("balance", balanceJSON);
				dataJSON.put("fund", lockedJSON);
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("error"));
			}
			//ConstatFinalUtil.OUTER_LOG.info(this.findid() + "--获取用户信息返回.--" + responseJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 下单交易
	 * 
	 * @return
	 */
	public JSONObject trade(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.trade(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new HashMap<String, String>();
		String tradeType = paramsMap.get("type");
		if(tradeType.equalsIgnoreCase(TradeEnum.TRADE_TYPE_SELL.getValue() + ""))
		{
			tradeType = "sell" ; 
		}else if(tradeType.equalsIgnoreCase(TradeEnum.TRADE_TYPE_BUY.getValue() + ""))
		{
			tradeType = "buy" ; 
		}
		
		requestMap.put("requestURL", this.serverUrl + "/api2/1/private/" + tradeType);
		
		/* 增加参数 */
		requestMap.put("currencyPair", paramsMap.get("moneytype"));
		requestMap.put("rate", paramsMap.get("price"));
		requestMap.put("amount", paramsMap.get("amount"));
		
		Map<String, String> headerMap = this.authSignRes(requestMap);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			
			if(responseJSON != null && "true".equalsIgnoreCase(responseJSON.get("result") + ""))
			{
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", responseJSON.get("orderNumber"));
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--下单交易返回--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "下单交易失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 撤销订单
	 * 
	 * @return
	 */
	public JSONObject cancelOrder(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.cancelOrder(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		Map<String, String> requestMap = new HashMap<String, String>();
		HTTPUtil httpUtil = new HTTPUtil();
		requestMap.put("requestURL", this.serverUrl + "/api2/1/private/cancelOrder");
		
		requestMap.put("orderNumber", paramsMap.get("order_id"));
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		requestMap.put("currencyPair", moneytype);
		
		Map<String, String> headerMap = this.authSignRes(requestMap);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap , requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			//ConstatFinalUtil.SYS_LOG.info("=--==>" + response);
			if(responseJSON != null && "true".equalsIgnoreCase(responseJSON.get("result") + ""))
			{
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", paramsMap.get("order_id"));
				resultJSON.put("data", dataJSON);
				
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--撤销订单返回.--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "撤销订单失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 获取用户挂单
	 * 
	 * {
			"success":1,
			"return":{
				"343152":{
					"pair":"btc_usd",
					"type":"sell",
					"amount":12.345,
					"rate":485,
					"timestamp_created":1342448420,
					"status":0
				},
				...
			}
		}
	 * 
	 * @param args
	 */
	public JSONObject getOrders(Map<String, String> requestMap)
	{
		long st = System.currentTimeMillis() ;
		//拼装目标数据
		JSONObject resultJSON = super.getOrders(requestMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		Map<String, String> paramsMap = new HashMap<String, String>();
		HTTPUtil httpUtil = new HTTPUtil();
		paramsMap.put("requestURL", serverUrl + "/api2/1/private/openOrders");
		
		String moneytype = requestMap.get("moneytype");
		moneytype = this.convertMoneyType(moneytype);
		paramsMap.put("currencyPair", moneytype);
		Map<String, String> headerMap = this.authSignRes(paramsMap);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, paramsMap);
			responseJSON = (JSONObject) JSON.parse(result);
			if(responseJSON != null && "true".equalsIgnoreCase(responseJSON.get("result") + ""))
			{
				JSONObject dataJSON = new JSONObject();
				
				JSONArray ordersArr = new JSONArray();
				JSONArray ordersResArr = (JSONArray) responseJSON.get("orders");
				for (Iterator iterator = ordersResArr.iterator(); iterator.hasNext();)
				{
					JSONObject ordersTemp = (JSONObject) iterator.next() ;
					JSONObject ordersJSON = this.convertOrders("", ordersTemp);
					ordersArr.add(ordersJSON);
				}
				
				dataJSON.put("ordersList", ordersArr);
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("message"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取挂单息返回.--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取挂单失败."
					+ paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 行情API
	 */
	public JSONObject queryTicker(Map<String, String> paramsMap)
	{

		HTTPUtil httpUtil = new HTTPUtil();
		String symbol = paramsMap.get("symbol");
		if ("ltc_cny".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL",
					"https://data.bter.com/api/1/ticker/ltc_cny");
		} else if ("btc_usd".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL", "https://data.bter.com/api/1/ticker/btc_usd");
		}else if ("btc_cny".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL", "https://data.bter.com/api/1/ticker/btc_cny");
		}else if ("ltc_usd".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL", "https://data.bter.com/api/1/ticker/ltc_usd");
		}


		JSONObject resultJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(paramsMap);
			resultJSON = (JSONObject) JSON.parse(result);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "行情API失败."
					+ paramsMap + ";原始信息:" + result , e);
		}
		return resultJSON;
	}

	/**
	 * depth(市场深度)
	 */
	public JSONObject queryDepth(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		
		HTTPUtil httpUtil = new HTTPUtil();

		Map<String, String> requestMap = new HashMap<String, String>();
		// 查询货币的类型
		String pair = this.convertMoneyType(paramsMap.get("moneytype"));
		requestMap.put("requestURL", dataServerUrl + "/api2/1/orderBook/" + pair);

		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			//responseJSON = (JSONObject) responseJSON.get(paramsMap.get("moneytype"));

			// 拼装符合条件的json数据
			JSONObject dataJSON = new JSONObject();

			int count = 0;
			// 按照规则排序的容器
			Map<Double, JSONObject> asksMap = new TreeMap<Double, JSONObject>();
			JSONArray asksResArr = new JSONArray();
			JSONArray asksArr = (JSONArray) responseJSON.get("asks");
			for (Iterator iterator = asksArr.iterator(); iterator.hasNext();)
			{
				JSONArray asksTempArr = (JSONArray) iterator.next();
				JSONObject askJSON = new JSONObject();
				askJSON.put("count", "1");
				askJSON.put("vol", asksTempArr.get(1) + "");
				askJSON.put("rate", asksTempArr.get(0) + "");

				asksMap.put(Double.valueOf(askJSON.get("rate") + ""), askJSON);
			}

			for (Iterator iterator = asksMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject asksTemp = (JSONObject) me.getValue();

				asksResArr.add(asksTemp);
				count++;
			}

			dataJSON.put("asks", asksResArr);

			// 按照规则排序的容器
			count = 0;
			Map<Double, JSONObject> bidsMap = new TreeMap<Double, JSONObject>(
					new Comparator<Double>()
					{
						@Override
						public int compare(Double o1, Double o2)
						{
							return o2.compareTo(o1);
						}
					});
			JSONArray bidsResArr = new JSONArray();
			JSONArray bidsArr = (JSONArray) responseJSON.get("bids");
			for (Iterator iterator = bidsArr.iterator(); iterator.hasNext();)
			{
				JSONArray bidsTempArr = (JSONArray) iterator.next();
				JSONObject bidsJSON = new JSONObject();
				bidsJSON.put("count", "1");
				bidsJSON.put("vol", bidsTempArr.get(1) + "");
				bidsJSON.put("rate", bidsTempArr.get(0) + "");

				bidsMap.put(Double.valueOf(bidsJSON.get("rate") + ""), bidsJSON);
			}

			for (Iterator iterator = bidsMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject bidsTemp = (JSONObject) me.getValue();

				bidsResArr.add(bidsTemp);
				count++;
			}
			dataJSON.put("bids", bidsResArr);

			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			resultJSON.put("data", dataJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "depth(市场深度)失败."
					+ paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * trades的格式,历史交易记录
	 */
	public JSONArray queryHistoryTrades(String symbol,
			Map<String, String> paramsMap)
	{

		HTTPUtil httpUtil = new HTTPUtil();

		if ("ltc_cny".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL",
					" https://www.okcoin.com/api/trades.do?symbol=ltc_cny");
		} else
		{
			paramsMap.put("requestURL",
					" https://www.okcoin.com/api/trades.do?");
		}
		JSONArray resultJSON = new JSONArray();
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(paramsMap);
			resultJSON = (JSONArray) JSON.parse(result);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "历史交易记录失败."
					+ paramsMap + ";原始信息:" + result , e);
		}
		return resultJSON;
	}

	/**
	 * 获取所有的行情
	 * 
	 * @return
	 */
	public JSONObject getTrade()
	{
		JSONObject resultJSON = new JSONObject();
		String hlUserURL = "http://www.okcoin.com/";
		try
		{
			// 请求服务
			Connection conn = Jsoup.connect(hlUserURL);
			conn.timeout(ConstatFinalUtil.REQ_CONNECT_TIMEOUT);

			conn.header(
					"Cookie",
					"abtest=\"16,34\\|18,41\\|22,60\\|14,29\\|15,33\"; userParamsCookie=trace=g1081; aburl=1; cy=160; __utma=1.543273261.1351234587.1351234587.1351234587.1; __utmz=1.1351234587.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _hc.v=\"\"22a8bf0b-7caf-468f-ac01-88534d000d02.1351216735\"\"; cye=zhengzhou; is=743412785865");
			conn.header(
					"User-Agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)");

			Document docu = conn.get();

			/* 买入成效价 */
			JSONArray mairuArr = new JSONArray();
			Elements mairuTrades = docu
					.getElementsByAttributeValue("class", "transaction").get(0)
					.child(1).children();
			for (Iterator iterator = mairuTrades.iterator(); iterator.hasNext();)
			{
				Element eleTemp = (Element) iterator.next();
				Elements tdsTemp = eleTemp.children();
				JSONObject mairuTempJSON = new JSONObject();
				// 1买入
				mairuTempJSON.put("type", tdsTemp.get(0).text());
				mairuTempJSON.put("price", tdsTemp.get(1).text());
				mairuTempJSON.put("num", tdsTemp.get(2).text());
				mairuArr.add(mairuTempJSON);
			}
			resultJSON.put("mairu", mairuArr);

			/* 买出成效价 */
			JSONArray maichuArr = new JSONArray();
			Elements maichuTrades = docu
					.getElementsByAttributeValue("class", "transaction").get(1)
					.child(1).children();
			for (Iterator iterator = maichuTrades.iterator(); iterator
					.hasNext();)
			{
				Element eleTemp = (Element) iterator.next();
				Elements tdsTemp = eleTemp.children();
				JSONObject maichuTempJSON = new JSONObject();
				// 1买入
				maichuTempJSON.put("type", tdsTemp.get(0).text());
				maichuTempJSON.put("price", tdsTemp.get(1).text());
				maichuTempJSON.put("num", tdsTemp.get(2).text());
				maichuArr.add(maichuTempJSON);
			}
			resultJSON.put("maichu", maichuArr);

		} catch (IOException e)
		{
			ConstatFinalUtil.OUTER_LOG.error("获取OKcoin的行情失败了", e);
		}
		return resultJSON;
	}

	public void setAuthJSON(JSONObject authJSON)
	{
		this.authJSON = authJSON;
	}

	@Override
	public String toString()
	{
		return "BterTradeServiceImplay [findid()=" + findWebsiteId() + "]";
	}

	@Override
	public JSONObject getOrdersSingle(Map<String, String> requestMap)
	{
		long st = System.currentTimeMillis() ;
		//拼装目标数据
		JSONObject resultJSON = super.getOrdersSingle(requestMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		
		Map<String, String> paramsMap = new HashMap<String, String>();
		HTTPUtil httpUtil = new HTTPUtil();
		paramsMap.put("requestURL", this.serverUrl + "/api2/1/private/getOrder");
		
		/* 增加参数 */
		paramsMap.put("orderNumber", requestMap.get("order_id"));
		String moneytype = this.convertMoneyType(requestMap.get("moneytype"));
		paramsMap.put("currencyPair", moneytype);
		
		Map<String, String> headerMap = this.authSignRes(paramsMap);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, paramsMap);
			responseJSON = (JSONObject) JSON.parse(result);
			if(responseJSON != null && "true".equalsIgnoreCase(responseJSON.get("result") + ""))
			{
				JSONObject dataJSON = new JSONObject();
				JSONObject valJSON = (JSONObject) responseJSON.get("order") ;
				JSONObject ordersResJSON = this.convertOrders("", valJSON);
				dataJSON.put("orders", ordersResJSON);
				resultJSON.put("data", dataJSON);
				
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取订单详情返回.--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取订单详情失败."
					+ paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	@Override
	public String parseMoneyType(String moneytype)
	{
		return null;
	}

	@Override
	public String findWebSiteName()
	{
		return "Gate";
	}

	@Override
	public JSONObject convertOrders(String moneytype, JSONObject ordersTempJSON)
	{
		JSONObject ordersJSON = new JSONObject();
		
		ordersJSON.put("order_id", ordersTempJSON.getString("orderNumber"));
		ordersJSON.put("price", ordersTempJSON.get("initialRate") + "");
		ordersJSON.put("deal_amount", ordersTempJSON.get("filledAmount"));
		ordersJSON.put("amount", ordersTempJSON.get("initialAmount") + "");
		/* avg_price:成交价格 */
		double deal_amount = Double.valueOf(ordersJSON.get("deal_amount") + "");
		double avg_price = 0 ; 
		if(deal_amount > 0 )
		{
			avg_price = Double.valueOf(ordersTempJSON.get("rate") + "");
		}
		ordersJSON.put("avg_price", avg_price);
		
		String pair = ordersTempJSON.get("currencyPair") + "";
		ordersJSON.put("symbol", pair);
		
		String type = ordersTempJSON.getString("type");
		if("buy".equalsIgnoreCase(type))
		{
			type = TradeEnum.TRADE_TYPE_BUY.getValue() + ""; 
		}else if("sell".equalsIgnoreCase(type))
		{
			type = TradeEnum.TRADE_TYPE_SELL.getValue() + "" ; 
		}
		ordersJSON.put("type", type + "");
		
		/* 订单的状态 */
		String status = ordersTempJSON.getString("status");
		/* 状态描述:
		 * 记录状态 DONE:完成; CANCEL:取消; REQUEST:请求中
		 * */
		if(status.equalsIgnoreCase("open"))
		{
			status = TradeEnum.TRADE_STATUS_DEAL_NO.getValue() + "" ;
		}else if(status.equalsIgnoreCase("cancelled"))
		{
			status = TradeEnum.TRADE_STATUS_CANCEL.getValue() + "" ;
		}else if(status.equalsIgnoreCase("DONE") || status.equalsIgnoreCase("closed"))
		{
			status = TradeEnum.TRADE_STATUS_DEALED.getValue() + "" ;
		}
		
		if(Double.valueOf(ordersJSON.get("deal_amount") + "") > 0
			&& Double.valueOf(ordersJSON.get("deal_amount") + "") < Double.valueOf(ordersJSON.get("amount") + ""))
		{
			/* 部分成交 */
			status = TradeEnum.TRADE_STATUS_DEAL_PART.getValue() + "" ;
		}
		ordersJSON.put("status", status);
		//处理下单时间
		Date createDate = new Date(Long.valueOf(ordersTempJSON.get("timestamp") + "") * 1000);
		ordersJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
		return ordersJSON;
	}
	
	@Override
	public JSONObject findAllTransPair(Map<String, String> paramsMap)
	{
		JSONObject resultJSON =  super.findAllTransPair(paramsMap);
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		String methodUrl = "/api2/1/marketinfo" ; 
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 公共代码 */
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("requestURL", serverUrl + methodUrl);
		
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(Collections.EMPTY_MAP,requestMap);
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			
			JSONObject dataJSON = new JSONObject();
			if("true".equalsIgnoreCase(responseJSON.getString("result")))
			{
				JSONArray resArr = responseJSON.getJSONArray("pairs");
				for (Iterator iterator = resArr.iterator(); iterator.hasNext();)
				{
					JSONObject resTempJSON = (JSONObject) iterator.next() ;
					JSONObject pairJSON = new JSONObject();
					
					String moneyType = "" ; 
					Set<String> keySet = resTempJSON.keySet() ; 
					for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();)
					{
						String keyTemp = (String) iterator2.next();
						moneyType = keyTemp ; 
						break; 
					}
					/*
					 * decimal_places: 价格精度
					    min_amount : 最小下单量
					    min_amount_a : 币种a [CURR_A]的最小下单量
					    min_amount_b : 币种b [CURR_B]的最小下单量
					    fee : 交易费
					    trade_disabled : 0表示未暂停交易，1表示已经暂停交易		
					 * {
				        //交易货币币种,小写;
				        "base_currency":"BTC",
				        //币对名称,小写;
				        "instrument_id":"BTC-USDT",
				        //最小交易数量
				        "min_size":"0.001",
				        //计价货币币种,小写;
				        "quote_currency":"USDT",
				        //交易货币数量精度
				        "size_increment":"0.00000001",
				        //交易价格精度
				        "tick_size":"0.1"
				    }
					 * */
					if(!moneyType.endsWith("usdt"))
					{
						continue ; 
					}
					
					JSONObject dataVal = (JSONObject) resTempJSON.get(moneyType);
					pairJSON.put("name", moneyType);
					pairJSON.put("min_size", dataVal.get("min_amount"));
					pairJSON.put("base_currency", "");
					pairJSON.put("quote_currency", "");
					pairJSON.put("size_increment", dataVal.get("decimal_places"));
					pairJSON.put("tick_size", dataVal.get("decimal_places"));
					/* 存储到结果中 */
					dataJSON.put(pairJSON.get("name") + "", pairJSON);
				}
			}
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			//ConstatFinalUtil.OUTER_LOG.info(this.findid() + "--获取用户信息返回.--" + responseJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败."
					+ requestMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}
}
